<?php

namespace App\Http\Middleware;

use App\Model\UserToken;
use Closure;

class CheckToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('token');
        $msg = $this->checkToken($token);
        if (!$token){
            return JsonResponse(1005,true,'请先登录',$request);
        }
        if ($msg !== true){
            return JsonResponse(1005,true,$msg);
        }
        return $next($request);
    }

    protected function checkToken($token){
        $exist = UserToken::where('token',$token)->first();
        if (!$exist){
            return '无效的身份信息';
        }
        if (time() >= $exist->overtime){
            return '登录信息已过期';
        }
        return true;
    }
}
